<?php

// No direct access
defined ('_JEXEC') or die();

jimport ('joomla.application.component.modeladmin');

class ShipnhanhModelOrder extends JModelAdmin
{
	public function getForm($data = array(), $loadData = true)
	{
		// Get form
		$form = $this->loadForm('com_shipnhanh.order', 'order', array('control' => 'jform', 'load_data' => $loadData));
		
		if (! $form)
		{
			return false;
		}
		else
		{
			return $form;
		}
	}
	
	public function loadFormData()
	{
		$data = $this->getItem();
		
		if (isset($data->id))
		{
			if (($webcharge = $this->getWebCharge($data->id)) > 0)
			{
				$data->webcharge = $webcharge;
			}
			
			$contactModel = JModel::getInstance('ContactInfo', 'ShipnhanhModel');
			$contact = $contactModel->getContactById($data->contact_info_id);
			$data->email = $contact->email;
			$data->address = $contact->address;
			$data->phone = $contact->phone;
			$data->customer = $contact->name;
		}
		
		$data->tax = number_format($data->tax, 2);
		$data->shipus = number_format($data->shipus, 2);
		$data->surcharge = number_format($data->surcharge, 2);
		$data->usprice = number_format($data->usprice, 2);
		$data->vnprice = number_format($data->vnprice, 2);
		
		return $data;
	}
	
	private function getWebCharge($id)
	{
		$result = -1;
		
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('((usprice + usprice * tax / 100 + shipus) * quantity) as webcharge');
		$query->from('#__sn_orders');
		$query->where('id=' . $id);
		
		$db->setQuery($query);
		
		$result = number_format($db->loadResult(), 2);
		
		return $result;
	}
	
	public function updateContactId($id, $contactId)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$fields = array('contact_info_id=' . $contactId);
		
		$query->update('#__sn_orders');
		$query->set($fields);
		$query->where('id=' . $id);
		$db->setQuery($query);
		$db->query();
	}
}